package com.nulldev.util.web.npswitcher;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.CellEditorListener;

import com.nulldev.util.io.FileUtil;
import com.nulldev.util.java.swing.extSwing.eAdvancedMessage;
import com.nulldev.util.java.swing.extSwing.eMessage;
import com.nulldev.util.java.swing.extSwing.lookandfeel.themes.ThemeApplier;
import com.nulldev.util.java.swing.extSwing.resources.eMessageType;
import com.nulldev.util.java.swing.font.FontManager;
import com.nulldev.util.math.MathUtil;
import com.nulldev.util.other.ArrayUtils;
import com.nulldev.util.string.StringsUtil;
import com.nulldev.util.sys.proxyswitcher.SystemProxySwitcher;
import com.nulldev.util.sys.proxyswitcher.SystemProxySwitcher.ProxyMode;
import com.nulldev.util.sys.proxyswitcher.SystemProxySwitcher.UseMethod;
import com.nulldev.util.threading.legacy.ThreadExecutor;
import com.nulldev.util.uri.URIUtil;
import com.nulldev.util.uri.URIUtil2;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;
import java.awt.event.ActionEvent;

public class nProxySwitcherUI extends JFrame {

	private JPanel contentPane;
	private JTable table;
	private JPanel panel;
	private JButton btnApply;
	private JButton btnRemove;

	/**
	 * Launch the application.
	 */
	public static void main() {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					nProxySwitcherUI frame = new nProxySwitcherUI();
					FontManager.setFont(FontManager.getFonts("MADE Evolve Sans", "Biko", "Highway Gothic", "Young"), 14);
					ThemeApplier.applyTheme(frame);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public nProxySwitcherUI() {
		setIconImage(Toolkit.getDefaultToolkit().getImage(nProxySwitcherUI.class.getResource("/com/nulldev/util/java/swing/nullutil_logo.png")));
		setTitle("nProxySwitcher");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 673, 416);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		contentPane.add(scrollPane, BorderLayout.CENTER);
		
		table = new JTable() {
			@Override
			public void paintComponent(final Graphics g) {
				((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
						RenderingHints.VALUE_ANTIALIAS_ON);
				super.paintComponent(g);
			}
		};
		table.setModel(new DefaultTableModel(
			new Object[][] {
			},
			new String[] {
				"Proxy IP", "Proxy Type", "Valid?"
			}
		));
		table.getTableHeader().setReorderingAllowed(false);
		scrollPane.setViewportView(table);
		
		panel = new JPanel();
		FlowLayout flowLayout = (FlowLayout) panel.getLayout();
		flowLayout.setVgap(0);
		flowLayout.setHgap(0);
		contentPane.add(panel, BorderLayout.SOUTH);
		
		btnApply = new JButton("Apply");
		btnApply.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				final int rowSelected = table.getSelectedRow();
				if (rowSelected <= -1) {
					return;
				}
				final ArrayList<Object> items = new ArrayList<Object>();
				for (int i = 0; i < table.getModel().getColumnCount(); i++) {
					items.add(table.getModel().getValueAt(rowSelected, i));
				}
				final String[] split = ((String) items.get(0)).split(":");
				if (StringsUtil.countChar(split[0], '.') == 3) {
					final InetSocketAddress addr = new InetSocketAddress(split[0], MathUtil.safeParseI(split[1], 8080));
					try {
						final boolean out = SystemProxySwitcher.applyProxy(SystemProxySwitcher.getMethod(),
								ProxyMode.MANUAL, new Proxy(java.net.Proxy.Type.HTTP,
										addr));
						System.out.println(out);
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}
			}
		});
		panel.add(btnApply);
		
		btnRemove = new JButton("Disable");
		btnRemove.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					final boolean removed = SystemProxySwitcher.applyProxy(SystemProxySwitcher.getMethod(), ProxyMode.DISABLED, Proxy.NO_PROXY);
					final eAdvancedMessage evm = eAdvancedMessage.main((removed ? eMessageType.SUCCESS : eMessageType.WARNING));
					evm.setWindowTitle("nProxySwitcher: Disable Proxies");
					if (removed) {
						evm.setMessageTitle("Proxies disabled");
						evm.setMessage("Proxies are no longer enabled.");
					}else {
						evm.setMessageTitle("Proxies weren't disabled");
						evm.setMessage("applyProxy(NO_PROXY) returned false!");
					}
					evm.waitForOK();
				}catch (Exception exa) {
					exa.printStackTrace();
				}
			}
		});
		panel.add(btnRemove);
		
		ThreadExecutor.execute(new Runnable() {
			
			@Override
			public void run() {
				try {
					nProxySwitcherUI.this.processTable();
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public void processTable() throws Exception {
		final List<String> proxies = FileUtil.readFile(
				FileUtil.safeCreate(
						FileUtil.HOME_DIRECTORY + "/nProxySwitcher/proxies.nprs"));
		final DefaultTableModel dtm = new DefaultTableModel(new Object[] {
				"Proxy IP", "Proxy Type", "Valid?"
		}, 0) {
			 @Override
			 public boolean isCellEditable(int row, int column) {
			      return false;
			 }
		};
		for (final String proxy : proxies) {
			final String[] split = proxy.split(":");
			if (StringsUtil.countChar(split[0], '.') == 3) {
				dtm.addRow(new Object[] {proxy, "HTTP", 
						URIUtil2.ProxyUtils.isValidProxy(split[0], MathUtil.safeParseI(split[1], 80), "https://www.google.com")});
			}
		}
		this.table.setModel(dtm);
		this.table.getTableHeader().setReorderingAllowed(false);
		final TableColumn tc = this.table.getColumnModel().getColumn(0);
	}
}
